<template>
    <div style="position: relative;">
        <Spin v-if="loading" fix></Spin>
        <div class="branch-selector">
            当前门店：
            <Select v-model="currentBranch" @on-change="handleChange" style="width:200px">
                <Option v-for="branch in branches" :key="branch.id" :value="branch.id">{{branch.name}}</Option>
            </Select>
        </div>
        <lock-setting
            model-type="branch"
            v-model="form"
            :default-config="defaultConfig">
        </lock-setting>
        <div style="margin-bottom:40px;padding-left:120px">
            <i-button :loading="submiting" @click="handleSubmit">保存修改</i-button>
        </div>

        <h2 class="margin-bottom-20 border-bottom" style="padding-bottom:20px">
            房源自定义列表
            <i-button @click="initData">刷新</i-button>
        </h2>

        <Table :loading="loadingTable" :data="tableData" :columns="columns"></Table>
    </div>
</template>

<script>
    import pick from 'lodash/pick'
import util from '@/libs/util'
import { Tag } from 'iview'; // eslint-disable-line
    import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
import lockSetting from '../components/lock-setting'

export default {
      name: 'lock-branch-setting',
      components: {
        lockSetting
      },
      data () {
        return {
          loading: false,
          loadingTable: false,
          submiting: false,
          tableData: [],
          form: {
            model: '',
            enable_alarm: false,
            alarm_time: '',
            alarm_unlock: 10
            // forbid_add_password: false,
            // forbid_add_tmp_password: false,
            // low_power: ''
          },
          defaultConfig: {},
          branches: [],
          currentBranch: '',
          columns: [
            { title: '房源名称', key: 'name' },
            { title: '开启预警', key: 'enableAlarm' },
            { title: '预警时长', key: 'alarmTime' },
            { title: '超时未锁', key: 'alarmUnlock' },
            {
              title: '短信推送',
              render: (h, p) => p.row.msgNotify.map(phone => <Tag>{phone}</Tag>)
            }
          ]
        }
      },
      async created () {
        this.branches = await this.fetchStores()
        if (this.branches.length) {
          this.currentBranch = this.branches[0].id
          this.initData()
          this.initSetting()
        }
      },
      methods: {
        fetchStores () {
          return new Promise((resolve, reject) => {
            dataCenter.getStores(this, (res, err) => {
              if (err || !res) {
                reject(new Error(''))
              }
              resolve(res)
            })
          })
        },
        handleChange () {
          this.initData()
          this.initSetting()
        },
        async initData () {
          this.loadingTable = true
          try {
            const res = await http.req(api.lock_settubg_list, null, { type: 'branch', value: this.currentBranch })
            if (!res) return
            this.tableData = res.map(item => {
              const { enable_alarm, alarm_time, alarm_unlock, msg_notify = [] } = item.lock_alarm_setting
              return {
                name: item.home_name,
                enableAlarm: enable_alarm === null ? '-' : enable_alarm ? '是' : '否',
                alarmTime: alarm_time === null ? '-' : alarm_time + '小时',
                alarmUnlock: alarm_unlock === null ? '-' : alarm_unlock + '分钟',
                msgNotify: msg_notify
              }
            })
          } catch (err) {
            console.log(err)
          } finally {
            this.loadingTable = false
          }
        },
        async initSetting () {
          this.loading = true
          try {
            const res = await http.req(api.lock_setting, null, { type: 'branch', value: this.currentBranch })
            if (!res) return
            this.defaultConfig = { ...res.defalut, ...res.parent, model: 'extend' }
            const result = util.lockSettingTranslate(res)
            this.form = pick(result, Object.keys(this.form))
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },
        async handleSubmit () {
          this.submiting = true
          try {
            const data = {
              ...this.form,
              alarm_unlock: 10,
              value: this.currentBranch,
              type: 'branch'
            }
            const res = await http.req(api.lock_setting_update, null, data)
            if (res) {
              this.$Message.success({
                content: '更改成功，相应提醒仅在配置完成后生效',
                duration: 4
              })
              this.handleChange()
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.submiting = false
          }
        }
      }
    }
</script>

<style scoped>
    .branch-selector{
        position: absolute;
        top: 0;
        right: 0;
    }
</style>
